package com.lean.android.ad.duration

import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.lean.android.ad.duration.database.DurationDatabase
import com.lean.android.ad.duration.database.entities.AppDurationEntity
import kotlinx.coroutines.launch

internal class AppDurationDetector(private val database: DurationDatabase) :
    DefaultLifecycleObserver {

    companion object {
        private const val TAG = "AppDuration"

    }

    private val durationWatcher by lazy {
        DurationWatcher()
    }

    private val appDurationDao by lazy {
        database.getAppDurationDao()
    }

    private val appScope by lazy {
        ProcessLifecycleOwner.get().lifecycleScope
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.d(TAG, "App enter foreground, onStart.")
        durationWatcher.start()
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        durationWatcher.stop { duration ->
            Log.d(TAG, "App enter background, stay $duration ms.")
            appScope.launch {
                appDurationDao.insert(
                    AppDurationEntity(duration = duration)
                )
            }
        }
    }
}